// 随机生成已有**人购买
function getRandom(){
   return Math.floor(Math.random()*90)
}


//加载更多页号
let i = 1
// 获取轮播图
function getBannerImg() {
    ajaxPromise({
        method: 'GET',
        url: 'http://api.yuguoxy.com/api/shop/banner',

    }).then(function (data) {
        if (data.resultCode == 1) {
            let banner = data.resultInfo.list
            shwoBannerImg(banner)
        }
    })
}

//显示轮播图
function shwoBannerImg(banner) {
    let str = ``
    let swiperStr = ``
    banner.forEach(item => {
        swiperStr = `<div class="swiper-slide"><img src="${item.url}" alt=""></div>`
        $('.swiper-wrapper').html(str += swiperStr)
    })
    let mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal', // 垂直切换选项
        loop: true, // 循环模式选项
        autoplay: true,

        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
        },

        // 如果需要前进后退按钮
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    })
}

function Tab(uls, ols) {
    this.uls = uls
    this.ols = ols
}
Tab.prototype.onTab = function () {
    for (let i = 0; i < this.uls.length; i++) {
        let _this = this
        this.uls[i].onclick = function () {
            //清除所有选项卡选中样式
            _this.clearTab()
            //设置active选项卡样式给当前选项
            //this表示当前点击元素
            this.classList.add('active')
            let index = this.getAttribute('data-index')
            _this.ols[index].classList.add('on')
        }
    }
}
Tab.prototype.clearTab = function () {
    for (let i = 0; i < this.uls.length; i++) {
        this.uls[i].classList.remove('active')
        this.ols[i].classList.remove('on')
    }
}
const uls = document.querySelectorAll('#nav>ul>li')
const ols = document.querySelectorAll('#content>ol>li')
let tab1 = new Tab(uls, ols)
tab1.onTab()






//显示tab数据
function showTabData(tab, el) {
    let str = ``
    tab.forEach((item, index) => {
        let tabStr = `
        <li class="ckeckLi">
            <p class="ckeckP" name="${index}">${item.name}</p>
        </li>
        `
        el.html(str += tabStr)
    })
}


//获取主页商品数据
function getProductList(i) {
    ajaxPromise({
        method: 'GET',
        url: 'http://api.yuguoxy.com/api/shop/list',
        data: {
            pageSize: 8,
            i,
        },

    }).then(function (data) {
        let {
            resultCode,
            resultInfo
        } = data
        if(resultCode==1){
            let productList =resultInfo.list
            showProductList(productList, $('.listIndex'))
        }

       
    })
}


//获取搜索框数据
function getInput() {
    $('.search>button').on('click', function () {
        console.log($('.search>input').val());
        let keyword = $('.search>input').val()
        // $('.search>input').val('')
        if ($('.search>input').val().length != 0) {
            ajaxPromise({
                method: 'GET',
                url: 'http://api.yuguoxy.com/api/shop/search',
                data: {
                    keyword
                }
            }).then(function (data) {
                let {
                    resultCode,
                    resultInfo
                } = data
                if(resultCode==1){
                    let productList = resultInfo.list
                    showSreachList(productList, $('.listSearch'))
                    $('.listIndex').hide()
                }
            })
        } else {
            alert("请输入搜索内容")
        }
    })
}

//显示搜索商品数据
function showSreachList(list, el) {
    let str = ``
    list.forEach(item => {
        let listStr = `
        <div class="itemCard" onclick="getCommodityId(${item.id})">
            <img src="${item.picture}" alt="商品图片">
            <div class="itemContent">
                <p>${item.product}</p>
                <div class="itemTag clearFix">
                    <p>淘宝</p>
                    <p>包邮</p>
                </div>
                <div class="itemFoot clearFix">
                    <div class="price fl">
                        <span>￥</span>
                        <span>${item.price}</span>
                    </div>
                    <div class="buy fl"><span>${getRandom()}</span>人已购买</div>
                    <div class="priceTag fr">
                        <span>${item.categoryname}</span>
                    </div>
                </div>
            </div>
        </div>
        `
        str += listStr
    });
    el.html(str)
}

//显示所有商品数据
function showProductList(list, el) {
    let str = ``
    list.forEach(item => {
        let listStr = `
        <div class="itemCard" onclick="getCommodityId(${item.id})">
            <img src="${item.picture}" alt="商品图片">
            <div class="itemContent">
                <p>${item.product}</p>
                <div class="itemTag clearFix">
                    <p>淘宝</p>
                    <p>包邮</p>
                </div>
                <div class="itemFoot clearFix">
                    <div class="price fl">
                        <span>￥</span>
                        <span>${item.price}</span>
                    </div>
                    <div class="buy fl"><span>${getRandom()}</span>人已购买</div>
                    <div class="priceTag fr">
                        <span>${item.categoryname}</span>
                    </div>
                </div>
            </div>
        </div>
        `
        str += listStr
    });
    el.append(str)
}

//加载更多
function more() {
    $('button[name="moreButton"]').on('click', function () {
        if ($(this).parent().parent().prop("id") == 'index') {
            i += 20
            $('button[name="moreButton"]').hide()
            getProductList(i)
            window.onscroll = function () {
                //文档内容实际高度（包括超出视窗的溢出部分）
                var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
                //滚动条滚动距离
                var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
                //窗口可视范围高度
                var clientHeight = window.innerHeight || Math.min(document.documentElement.clientHeight, document.body.clientHeight);
                if (clientHeight + scrollTop >= scrollHeight) {
                    i += 20
                    getProductList(i)
                }
            }
        }
        
    })
}

//获取商品ID
function getCommodityId(id) {
    //事件委托
    console.log(id);
    location.href = './detail.html?id=' + id

}

getBannerImg()
getInput()
getProductList()
showUserName()
more()